package com.microframework.base.core.util.sql;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.SQLException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

public class DataSourceValidator {
    
    /**
     * 验证数据源配置是否正确
     * 
     * @param url      数据库连接URL
     * @param driver   驱动类名
     * @param username 用户名
     * @param password 密码
     * @param timeout  连接超时时间（秒）
     * @return 验证结果对象
     */
    public static ValidationResult validateDataSource(String url, String driver, 
                                                     String username, String password, 
                                                     int timeout) {
        ValidationResult result = new ValidationResult();
        
        try {
            // 1. 验证驱动类是否可用
            validateDriverClass(driver);
            result.setDriverValid(true);
            
            // 2. 尝试建立数据库连接
            Connection conn = createConnection(url, driver, username, password, timeout);
            if (conn != null) {
                result.setConnectionValid(true);
                
                // 3. 验证连接是否有效
                result.setConnectionAlive(testConnection(conn));
                
                // 4. 关闭连接
                conn.close();
            }
        } catch (Exception e) {
            result.setErrorMessage(e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 验证驱动类是否可用
     */
    private static void validateDriverClass(String driverClass) throws ClassNotFoundException {
        try {
            Class.forName(driverClass);
        } catch (ClassNotFoundException e) {
            throw new ClassNotFoundException("数据库驱动类未找到: " + driverClass, e);
        }
    }
    
    /**
     * 创建数据库连接
     */
    private static Connection createConnection(String url, String driver, 
                                              String username, String password, 
                                              int timeout) throws SQLException {
        Properties props = new Properties();
        props.setProperty("user", username);
        props.setProperty("password", password);
        
        // 设置连接超时和读取超时
        props.setProperty("connectTimeout", String.valueOf(TimeUnit.SECONDS.toMillis(timeout)));
        props.setProperty("socketTimeout", String.valueOf(TimeUnit.SECONDS.toMillis(timeout)));
        
        try {
            @SuppressWarnings("deprecation")
			Driver driverInstance = (Driver) Class.forName(driver).newInstance();
            return driverInstance.connect(url, props);
        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
            throw new SQLException("驱动实例化失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 测试连接是否有效
     */
    private static boolean testConnection(Connection conn) {
        try {
            // 执行简单的验证查询
            return conn.createStatement().execute("SELECT 1");
        } catch (SQLException e) {
            return false;
        }
    }
    
    /**
     * 验证结果对象
     */
    public static class ValidationResult {
        private boolean driverValid;
        private boolean connectionValid;
        private boolean connectionAlive;
        private String errorMessage;
        
        // Getters and Setters
        public boolean isValid() {
            return driverValid && connectionValid && connectionAlive;
        }
        
        public boolean isDriverValid() {
            return driverValid;
        }

        public void setDriverValid(boolean driverValid) {
            this.driverValid = driverValid;
        }

        public boolean isConnectionValid() {
            return connectionValid;
        }

        public void setConnectionValid(boolean connectionValid) {
            this.connectionValid = connectionValid;
        }

        public boolean isConnectionAlive() {
            return connectionAlive;
        }

        public void setConnectionAlive(boolean connectionAlive) {
            this.connectionAlive = connectionAlive;
        }

        public String getErrorMessage() {
            return errorMessage;
        }

        public void setErrorMessage(String errorMessage) {
            this.errorMessage = errorMessage;
        }
        
        @Override
        public String toString() {
            if (isValid()) {
                return "✅ 数据源配置验证成功";
            }
            
            StringBuilder sb = new StringBuilder("❌ 数据源配置验证失败：");
            if (!driverValid) {
                sb.append("\n- 驱动类加载失败");
            }
            if (!connectionValid) {
                sb.append("\n- 数据库连接建立失败");
            }
            if (connectionValid && !connectionAlive) {
                sb.append("\n- 连接建立但无法执行查询");
            }
            if (errorMessage != null) {
                sb.append("\n- 错误信息: ").append(errorMessage);
            }
            
            return sb.toString();
        }
    }
    
    // 使用示例
    public static void main(String[] args) {
        // MySQL 示例
        ValidationResult result = validateDataSource(
            "jdbc:mysql://localhost:3306/testdb?useSSL=false&serverTimezone=UTC",
            "com.mysql.cj.jdbc.Driver",
            "root",
            "password",
            5
        );
        
        System.out.println(result);
        System.out.println("配置是否有效: " + result.isValid());
        
        // PostgreSQL 示例
        result = validateDataSource(
            "jdbc:postgresql://localhost:5432/testdb",
            "org.postgresql.Driver",
            "postgres",
            "password",
            5
        );
        
        System.out.println(result);
    }
}